﻿function VIU_Edit_ViewModel() {
    var self = this;
    self.title = ko.observable('').extend({
        required: { params: true, message: "标题必填。" }
    });
    self.content = ko.observable('').extend({
        required: { params: true, message: "内容必填。" }
    });
    self.stars = ko.observable(3);
    self.hits = ko.observable(0);
    self.author = ko.observable();
    self.allowComment = ko.observable(true);
    self.isElite = ko.observable(false);
    self.isOnTop = ko.observable(false);
    self.isHeadline = ko.observable(false);
    self.categoryId = ko.observable('').extend({
        required: { params: true, message: "请选择类别。" }
    });
    self.categories = ko.observableArray([]);//类别   
    self.showCategoryRadio = function (data) {

        return data.children.length < 0;
    }
    //self.categoryChecked = function (data, event) {
    //    //var $this = $(event.target);

    //    if (event.target.checked) {
    //        self.VIUPropertys.push(data);
    //    } else {
    //        self.VIUPropertys.remove(data);
    //    }
    //    return true;
    //}
    self.fieldIds = ko.observableArray([]).extend({
        required: { params: true, message: "请选择领域。" }
    });
    self.fields = ko.observableArray([]);//领域
    self.tagIds = ko.observableArray([]).extend({
        required: { params: true, message: "请选择属性。" }
    });
    self.multiMedias = ko.observableArray([]);//多媒体附件
    //VIU的属性
    self.VIUPropertys = ko.observableArray([]);
    //性质
    self.natures = ko.observableArray([]);
    self.nature = ko.observable();
    //关注度
    self.interests = ko.observableArray([]);
    self.interest = ko.observable();
    //重要性
    self.importances = ko.observableArray([]);
    self.importance = ko.observable();
    //风格
    self.styles = ko.observableArray([]);
    self.style = ko.observable();
    self.eventDay = ko.observable();//发生日期
    self.publishDay = ko.observable();//发布日期
    self.errors = ko.validation.group(self);

    self.saveVIUPropertys = ko.observableArray([]);
    self.init = function (vidId) {
        self.natures.push({ name: '社会', value: 0 });
        self.natures.push({ name: '营销', value: 1 });
        self.natures.push({ name: '知识', value: 2 });

        if (vidId.length > 0) {
            app.getJSON("/VIU/GetInfo",
                {
                    id: vidId
                },
                function (res) {
                    if (res.newData != null) {
                        self.title(res.newData.title);
                        self.stars(res.newData.stars);
                        self.hits(res.newData.hits);
                        self.author(res.newData.author);
                        self.content(res.newData.content);
                        self.tagIds(res.newData.tagIds);
                        self.fieldIds(res.newData.fieldIds);
                        self.categoryId(res.newData.categoryId);
                        self.allowComment(res.newData.allowComment);
                        self.isElite(res.newData.isElite);
                        self.isOnTop(res.newData.isOnTop);
                        self.isHeadline(res.newData.isHeadline);
                        self.nature(res.newData.nature);
                        self.interest(res.newData.interest);
                        self.importance(res.newData.importance);
                        self.style(res.newData.style);
                        self.eventDay(res.newData.eventDay);
                        self.publishDay(res.newData.publishDay);

                        res.newData.multiMedias.forEach(function (item) {
                            var pvm = new PictrueViewModel();
                            pvm.src = item.thumbUrl;
                            pvm.isDefault(item.isDefault);
                            self.multiMedias.push(pvm);
                        });

                    }


                    $("#editor").summernote({
                        height: 250,
                        lang: 'zh-CN',
                        callbacks: {
                            onKeyup: function () {
                                var content = $("#editor").summernote("code");
                                self.content(content);
                                console.log("summernote_onKeyup");
                            },
                            onblur: function (e) {
                                var content = $("#editor").summernote("code");
                                self.content(content);
                                console.log("summernote_onblur");
                            }
                        }
                    });
                });

        }
    }
    self.biuldPropertyData = function (newData) {
        if (newData == null) {
            return;
        }
        newData.forEach(function (item, index) {
            item.selected = ko.observable(true);
            //一级筛选

            item.itemClick = function (data) {
                data.selected(!data.selected());
                self.VIUPropertys.push(data);
                return true;
            };
       
            item.children.forEach(function (item1, index1) {
                item1.selected = ko.observable(false);
                item1.unselect = function (data1) {
                    ko.utils.arrayForEach(self.VIUPropertys(), function (item2) {

                        ko.utils.arrayForEach(item2.children, function (item4) {

                            if (item4.id === data1.id) {
                                item4.selected(false);
                                return false;
                            }
                            return true;
                        });

                        self.saveVIUPropertys.remove(data1);
                    });
                }
                //二级筛选
                item1.itemClickFuc = function (data1) {
                    data1.selected(true);
                    self.VIUPropertys.push(data1);
                    return true;
                };

                item1.tags.forEach(function (tagItem) {

                    tagItem.selected = ko.observable(false);
                    tagItem.itemClick = function (data) {
                        self.saveVIUPropertys.push(data);
                    }
                    tagItem.unselect=function(data) {
                        self.saveVIUPropertys.remove(data);
                    }
                });
            });
   
            item.tags.forEach(function (tagItem) {
                tagItem.selected = ko.observable(false);
                tagItem.itemClick = function (data) {
                    self.saveVIUPropertys.push(data);
                }
                tagItem.unselect = function (data) {
                    self.saveVIUPropertys.remove(data);
                }
            });
            
            self.categories.push(item);
        });

    }
    //首字母列表
    self.initialList = ko.dependentObservable(function () {
        //准备字母表数据
        var data = [];
        data.push({ name: '全部', style: ko.observable('btn-success') });
        for (var i = 0; i <= 25; i++) {
            data.push({
                name: String.fromCharCode((65 + i)), style: ko.observable('btn-default')
            });
        }
        data.push({ name: '*', style: ko.observable('btn-default') });

        return data;
    });
    //已经选取的字母表
    self.selectedInitial = '全部';
    self.initialClick = function (data) {
        ko.utils.arrayForEach(self.initialList(), function (item) {
            item.style("btn-default");
        });
        data.style("btn-success");
        self.selectedInitial = data.name;

        self.pageIndex(Math.random());
    }
    self.keyword = ko.observable("");
    self.saveForm = function () {
        app.ajax({
            type: "POST",
            url: '/VIU/Save',
            data: $(".VIUForm").serialize(),
            dataType: "json",
            success: function (data) {

                if (data.errors.length > 0) {
                    swal("出错啦！", data.errors, "error");
                } else {
                    window.app.loadUI("/VIU/");
                }

            },
            error: function (xmlHttpRequest, textStatus, errorThrown) {
                window.app.message("服务器异常。" + textStatus);
            }
        });
    }

    self.list = ko.observableArray();
    self.pageSize = ko.observable(100);
    self.pageIndex = ko.observable(0); //要访问的页码
    self.totalCount = ko.observable(0); //总记录数
    self.loadingState = ko.observable(true);
    self.maxPageIndex = ko.observable(0);

    self.pagedList = ko.dependentObservable(function () {
        var size = self.pageSize();
        var start = parseInt(self.pageIndex()) * size;
        var data = [];
        ko.utils.arrayForEach(self.VIUPropertys(), function (item) {
            if (!item.selected()) {
                return false;
            }
            ko.utils.arrayForEach(item.tags, function (item4) {

                if (item.id === item4.categoryId
                    && (self.keyword().length === 0 || item4.name.indexOf(self.keyword()) > -1)
                    && (self.selectedInitial === "全部" || self.selectedInitial === item4.initial)) {

                    data.push(item4);
                }
            });
            return true;
        });
        self.totalCount(data.length);

        self.maxPageIndex(Math.ceil(data.length / self.pageSize()) - 1);

        return data.slice(start, start + size);
    });

    self.search = function () {
        self.pageIndex(Math.random());
    }


    self.previousPage = function () {
        if (self.pageIndex() > 0) {
            self.pageIndex(self.pageIndex() - 1);
        }
    };
    self.nextPage = function () {
        if (self.pageIndex() < self.maxPageIndex()) {
            self.pageIndex(self.pageIndex() + 1);
        }
    };
    self.allPages = ko.dependentObservable(function () {
        var pages = [];

        switch (self.pageIndex()) {
            case 0:
            case 1:
                for (var ii = 0; ii < Math.min(5, self.maxPageIndex()) ; ii++) {
                    pages.push({ pageNumber: parseInt(ii + 1) });
                }
                break;
            default:
                var pageIndexTag = self.pageIndex();
                if (pageIndexTag < 2) {
                    pageIndexTag = pageIndexTag + 2;
                }
                for (var i = pageIndexTag - 2; i <= pageIndexTag + 2 ; i++) {
                    if (i > self.maxPageIndex()) {
                        break;
                    }
                    pages.push({ pageNumber: parseInt(i + 1) });
                }
                break;

        }

        return pages;
    });
    self.moveToPage = function (index) {
        self.pageIndex(index);
    };

}

function PictrueViewModel() {
    var me = this;
    me.id = ko.observable('');
    me.src = ko.observable('');
    me.isDefault = ko.observable(false);
    me.default = function (root) {
        ko.utils.arrayForEach(root.multiMedias(), function (item) {
            item.isDefault(false);
        });
        me.isDefault(!me.isDefault());
    }
    me.removeMe = function (root) {
        swal({
            title: "请确认是否删除？",
            text: "您正在进行删除操作，该操作不可逆!",
            type: "warning",
            showCancelButton: true,
            confirmButtonClass: "btn-danger"
        }).then(function (isConfirm) {
            if (isConfirm === true) {
                root.multiMedias.remove(me);
                swal("已经删除", "你已经删除成功！", "success");
            }
        });
    }
}